﻿using OpenQA.Selenium;
using OpenQA.Selenium.PhantomJS;
using OpenQA.Selenium.Support.UI;
using Spider.Entitys.Spider;
using System;
using System.Diagnostics;
using System.Threading;

namespace SpiderCore.Downloader
{
    public sealed class WebDriverDownloader : IDownloader
    {
        private IWebDriver driver = null;
        public void SetPhantomJSDriver(PhantomJSDriver driver)
        {
            this.driver = driver;
        }

        #region 构造函数
        public WebDriverDownloader()
        {
        }

        public WebDriverDownloader(PhantomJSDriver driver)
        {
            this.driver = driver;
        }
        #endregion

        public ResponseModel Download(RequestModel request)
        {
            try
            {
                Thread.Sleep(500);
                //启动计时器
                var stopwatch = new Stopwatch();
                string html = "";

                if (driver == null)
                {
                    driver = new PhantomJSDriver(GetPhantomJSDriverService());
                }

                try
                {
                    driver.Navigate().GoToUrl(request.Url);
                }
                catch (Exception ex)
                {
                    try
                    {
                        driver.Navigate().GoToUrl(request.Url);
                    }
                    catch
                    {

                    }
                }

                driver.FindElement(By.Id("yc")).Click();
                WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(1000));
                wait.Until<bool>((d) =>
                {
                    string text = driver.FindElement(By.Id("yc")).Text;
                    string tempText = text.Substring(0, 4);
                    if (tempText.Equals("点击关闭"))
                    {
                        return true;
                    }
                    return false;
                });
                html = driver.PageSource;

                //停止计时器
                stopwatch.Stop();
                request.DownloadTime = stopwatch.Elapsed.TotalMilliseconds;
                request.CrawlTime = DateTime.Now;
                ResponseModel resp = new HtmlResponseModel()
                {
                    Html = html,
                    Request = request,

                };
                return resp;
            }
            catch (Exception e)
            {

            }
            return null;
        }


        private PhantomJSDriverService GetPhantomJSDriverService()
        {
            PhantomJSDriverService pds = PhantomJSDriverService.CreateDefaultService();
            return pds;
        }


    }
}
